#define _CRT_SECURE_NO_WARNINGS 1
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseKGroup(ListNode* head, int k)
    {
        ListNode* cur = head;
        int n = 0;
        while (cur)
        {
            cur = cur->next;
            ++n;
        }
        ListNode* new_head = new ListNode();
        ListNode* prev = new_head;
        for (int i = 0; i < n / k; i++)
        {
            ListNode* tail = head;
            for (int j = 0; j < k; j++)
            {

                ListNode* next = head->next;
                head->next = prev->next;
                prev->next = head;
                head = next;
            }
            prev = tail;
        }
        while (head)
        {
            ListNode* next = head->next;
            prev->next = head;
            head = head->next;
            prev = prev->next;
        }
        return new_head->next;
    }
};